<?php
/**
 * Created by PhpStorm.
 * Author: Shadow
 * Date: 2022/8/25
 * Time: 2:57 下午
 * description: Token.php
 */

namespace app\adminapi\services;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\Exception;


class Token
{

    private $key = '2006A';

    private $expired = 86400;

    /**
     * 生成token令牌
     */
    public function createToken($user_id){
        // 生成jwttoken
        $payload = [
            'iss' => 'http://adminpi.pyg.com',
            'aud' => 'http://www.pyg.com',
            'iat' => time(),
            'nbf' => time(),
            'user_id' => $user_id,
            'exp' => time() + $this->expired
        ];

        /**
         * IMPORTANT:
         * You must specify supported algorithms for your application. See
         * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
         * for a list of spec-compliant algorithms.
         */
        $jwt = JWT::encode($payload, $this->key, 'HS256');
        return $jwt;
    }

    /**
     * 验证token令牌
     */
    public function verifyToken(){
        try {
            # 接收客户端传递给我的token
            $jwt = $this->getAuth();
            # 判断token是否已经失效
            $deleteToken = cache('deleteToken') ?: [];
            if (in_array($jwt,$deleteToken)) {
                throw new Exception("token认证失败",2001);
            }

            $decoded = JWT::decode($jwt, new Key($this->key, 'HS256'));
            $decoded = (array)$decoded;
            if (!isset($decoded['user_id'])) {
                throw new Exception("请先登录",2001);
            }

            $user_id = $decoded['user_id'];

            return  $user_id;
        }catch (\Exception $exception) {
            throw new Exception("token认证失败",2001);
        }
    }


    /**
     * 删除token
     */
    public function deleteToken(){
        $jwt = $this->getAuth();
        $deleteToken = cache('deleteToken') ?: [];
        array_push($deleteToken,$jwt);
        // 重新保存缓存
        cache('deleteToken',$deleteToken,86400);
        return true;
    }


    /**
     * 获取认证信息
     */
    public function getAuth(){
        $jwt = $_SERVER['HTTP_AUTHORIZATION'];
        $jwt = str_replace("Bearer ","",$jwt);
        return $jwt;
    }
}